package io.command;

import io.*;
import io.command.result.IOIntResult;
import io.command.result.IOResult;
import card.Cardset;

/**
 * Command for inputing cards
 * 
 * 
 * @version 1.0.2
 */
public class CardInputCommand extends IOCommand {

	private Cardset availableCards;

	public CardInputCommand(IIO io, Cardset cards) {
		super(io);
		this.availableCards = cards;
	}

	/**
	 * check if the card index is valid input
	 * 
	 * @param str
	 * @param c
	 * @return
	 */
	private boolean isValidNum(String str, Cardset c) {
		if (isInteger(str) && Integer.parseInt(str) >= 0
				&& Integer.parseInt(str) <= c.count() - 1) {
			return true;
		}
		io.println("Fail input");
		return false;
	}

	/**
	 * Check if the input is integer number
	 * 
	 * @param s
	 * @return
	 */
	private boolean isInteger(String s) {
		try {
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return false;
		}
		return true;
	}

	/**
	 * Command details
	 */
	@Override
	public IOResult execute() {
		String str = "";

		do {
			str = io.getNextInput();
			if (str.charAt(0) == 't')
				return new IOIntResult(-1);
		} while (!isValidNum(str, availableCards));
		int result = Integer.parseInt(str);

		return new IOIntResult(result);
	}

}
